package com.jiawa.train.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiawa.train.business.domain.DailyTrainSeat;
import com.jiawa.train.business.domain.DailyTrainCarriage;
import com.jiawa.train.business.domain.DailyTrainTicket;
import com.jiawa.train.business.enums.SeatColEnum;
import com.jiawa.train.business.mapper.DailyTrainSeatMapper;
import com.jiawa.train.business.req.DailyTrainSeatQueryReq;
import com.jiawa.train.business.req.DailyTrainSeatSaveReq;
import com.jiawa.train.business.resp.DailyTrainSeatQueryResp;
import com.jiawa.train.business.service.DailyTrainSeatService;
import com.jiawa.train.business.service.DailyTrainCarriageService;
import com.jiawa.train.common.resp.PageResp;
import com.jiawa.train.common.util.SnowUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class DailyTrainSeatServiceImpl extends ServiceImpl<DailyTrainSeatMapper, DailyTrainSeat> implements DailyTrainSeatService {
    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainSeatServiceImpl.class);

    @Resource
    private DailyTrainCarriageService dailyTrainCarriageService;
    @Resource
    private DailyTrainSeatMapper dailyTrainSeatMapper;

    public void save(DailyTrainSeatSaveReq req) {
        DateTime now = DateTime.now();
        DailyTrainSeat dailyTrainSeat = BeanUtil.copyProperties(req, DailyTrainSeat.class);
        if (ObjectUtil.isNull(dailyTrainSeat.getId())) {
            dailyTrainSeat.setId(SnowUtil.getSnowflakeNextId());
            dailyTrainSeat.setCreateTime(now);
            dailyTrainSeat.setUpdateTime(now);
            this.save(dailyTrainSeat);
        } else {
            dailyTrainSeat.setUpdateTime(now);
            this.updateById(dailyTrainSeat);
        }
    }

    public PageResp<DailyTrainSeatQueryResp> queryList(DailyTrainSeatQueryReq req) {
        LambdaQueryWrapper<DailyTrainSeat> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(DailyTrainSeat::getDailyTrainCode)
                .orderByAsc(DailyTrainSeat::getCarriageIndex)
                .orderByAsc(DailyTrainSeat::getCarriageSeatIndex);
        if (ObjectUtil.isNotEmpty(req.getTrainCode())) {
            wrapper.eq(DailyTrainSeat::getDailyTrainCode, req.getTrainCode());
        }
        LOG.info("查询页码：{}", req.getPage());
        LOG.info("每页条数：{}", req.getSize());
        Page<DailyTrainSeat> page = new Page<>(req.getPage(), req.getSize());
        Page<DailyTrainSeat> dailyTrainSeatPage = this.page(page, wrapper);
        LOG.info("总行数：{}", dailyTrainSeatPage.getTotal());
        LOG.info("总页数：{}", dailyTrainSeatPage.getPages());
        List<DailyTrainSeatQueryResp> list = BeanUtil.copyToList(dailyTrainSeatPage.getRecords(), DailyTrainSeatQueryResp.class);
        PageResp<DailyTrainSeatQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(dailyTrainSeatPage.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    public void delete(Long id) {
        this.removeById(id);
    }


    @Transactional
    public void genDaily(Date date, String dailyTrainCode) {
        // 清空当前车次的所有座位记录
        LambdaQueryWrapper<DailyTrainSeat> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DailyTrainSeat::getDailyTrainCode, dailyTrainCode);
        this.remove(wrapper);

        // 查找当前车次的所有车厢
        List<DailyTrainCarriage> carriages = dailyTrainCarriageService.selectByDailyTrainCode(dailyTrainCode);
        // 循环生成每个车厢的座位

        for (DailyTrainCarriage carriage : carriages) {
            Integer rowCount = carriage.getRowCount();
            String seatType = carriage.getSeatType();
            Integer seatCount = carriage.getSeatCount();
            Integer index = carriage.getIndex();

            for (int row = 1; row <= rowCount; row++) {
                for (SeatColEnum seatColEnum : SeatColEnum.values()) {

                    DailyTrainSeat dailyTrainSeat = new DailyTrainSeat();
                    dailyTrainSeat.setId(SnowUtil.getSnowflakeNextId());
                    dailyTrainSeat.setDailyTrainCode(dailyTrainCode);
                    dailyTrainSeat.setCarriageIndex(index);
                    dailyTrainSeat.setRow(StrUtil.fillBefore(String.valueOf(row), '0', 2));
                    dailyTrainSeat.setCol(seatColEnum.getCode());
                    dailyTrainSeat.setSeatType(seatType);
                    dailyTrainSeat.setCarriageSeatIndex(seatCount++);
                    this.save(dailyTrainSeat);
                }
            }
        }
    }

    public List<DailyTrainSeat> selectByDailyTrainCode(String dailyTrainCode) {
        LambdaQueryWrapper<DailyTrainSeat> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DailyTrainSeat::getDailyTrainCode, dailyTrainCode)
                .orderByAsc(DailyTrainSeat::getCarriageIndex)
                .orderByAsc(DailyTrainSeat::getCarriageSeatIndex);
        return this.list(wrapper);
    }

    public int countSeat(Date date, String trainCode, String seatType) {
        QueryWrapper<DailyTrainSeat> wrapper = new QueryWrapper<>();
        wrapper.eq("date", date)
                .eq("train_code", trainCode)
                .eq("seat_type", seatType);
        long count = dailyTrainSeatMapper.selectCount(wrapper);
        if (count == 0L) {
            return -1;
        }
        return (int) count;
    }
} 